package sourceagile.server.classRepositories.subversionFileRepository;

import java.io.ByteArrayInputStream;

import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.diff.SVNDeltaGenerator;

/** 
 * 
 * 
 * @MainFeature 
 */

public class AddFile {

	public static void save(String repositoryURL, String username,
			String password, String parentFolderName, String newSubFolderName,
			String fileName, String newFileContent) {

		try {

			SVNRepository repository = SubversionRepositoryConnection.connect(
					repositoryURL, username, password);

			String logMessage = "Creating file: " + fileName;

			ISVNEditor repositoryEditor = repository.getCommitEditor(
					logMessage, null);

			repositoryEditor.openRoot(-1);

			repositoryEditor.openDir(parentFolderName, -1);

			if (newSubFolderName != null) {

				repositoryEditor.addDir(newSubFolderName, null, -1);
			}

			repositoryEditor.addFile(fileName, null, -1);

			repositoryEditor.applyTextDelta(fileName, null);

			SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator();
			String checksum = deltaGenerator.sendDelta(fileName,
					new ByteArrayInputStream(newFileContent.getBytes()),
					repositoryEditor, true);

			repositoryEditor.closeFile(fileName, checksum);

			repositoryEditor.closeDir();

			repositoryEditor.closeEdit();

		} catch (SVNException e) {

			e.printStackTrace();
		}

	}

}
